
import 'package:dio/dio.dart';
import 'package:dio_log/dio_log.dart';

import '/api/api.dart';
import 'dio_interceptors.dart';
import 'http_config.dart';

enum RequestType{
  POST,
  GET,
  PUT,
  DEL,
}
class HttpUtil{
  static Dio? _dio;
  HttpUtil._privateConstructor();
  static HttpUtil? _instance = HttpUtil._privateConstructor();
  static HttpUtil? get instance { return _instance;}

  static HttpUtil? getInstance() {
    if (_dio == null) {
      _instance!._init();
    }
    return _instance;
  }

  _init() {
    _dio = Dio();
    _dio!.options.baseUrl = Api.baseUrl;
    _dio!.options.connectTimeout = HttpConfig.connectTimeout;
    _dio!.options.receiveTimeout = HttpConfig.receiveTimeout;
    _dio!.interceptors.add(LogInterceptors()); //是否开启请求日志
    _dio!.interceptors.add(DioLogInterceptor()); //调试用的
  }

  Future<Map<String, dynamic>?> get<T>(url,{Map<String,dynamic>? params,Options? options,CancelToken? cancelToken,ProgressCallback? onReceiveProgress}) async{
    Response<Map<String, dynamic>>? map = await _dio!.get(url,queryParameters: params,options: options,cancelToken: cancelToken,onReceiveProgress:onReceiveProgress);
    return map.data;
  }

  Future<Map<String, dynamic>?> post<T>(url,{Map<String,dynamic>? params,dynamic data}) async{
    Response<Map<String, dynamic>> map =  await _dio!.post(url,queryParameters: params,data: data);
    return map.data;
  }

  Future<Map<String, dynamic>?> postData<T>(url,{Map<String,dynamic>? params,dynamic data}) async{
    Response<Map<String, dynamic>> map =  await _dio!.post(url,queryParameters: params,data: data);
    return map.data;
  }

  Future<Map<String, dynamic>?> delete<T>(url,{Map<String,dynamic>? params,withLoading}) async{
    Response<Map<String, dynamic>> map =  await _dio!.delete("path");
    return map.data;
  }

  Future<Response> download(url,{Map<String,dynamic>? params,String savePath:'/storage/emulated/0/',}) async{
    Response response =  await _dio!.download(url,savePath);
    return response.data;
  }

  Future<Map<String, dynamic>?> del<T>(url,{Map<String,dynamic>? params,withLoading}) async{
    Response<Map<String, dynamic>> map =  await _dio!.delete("path");
    return map.data;
  }
}